package xin.lhuo.we.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qiniu.common.QiniuException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.lhuo.we.server.dao.PhotoMapper;
import xin.lhuo.we.server.entity.Photo;
import xin.lhuo.we.server.entity.QiNiuPutRet;
import xin.lhuo.we.server.enums.QiNiuCodeEnum;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.exception.WeException;
import xin.lhuo.we.server.properties.QiNiuProperties;
import xin.lhuo.we.server.service.IPhotoService;
import xin.lhuo.we.server.utils.DateUtils;
import xin.lhuo.we.server.utils.InputStreamUtil;
import xin.lhuo.we.server.utils.QiNiuUtil;
import xin.lhuo.we.server.vo.PhotosVo;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static xin.lhuo.we.server.enums.ResultEnum.PARAM_ERROR;

/**
 * @author Lhuo
 * @date 2019/5/9 16:06
 */
@Slf4j
@Service(value = "photoServer")
public class PhotoServiceImpl implements IPhotoService {
    private final QiNiuProperties qiNiuProperties;

    private final PhotoMapper photoMapper;

    @Autowired
    public PhotoServiceImpl(QiNiuProperties qiNiuProperties, PhotoMapper photoMapper) {
        this.qiNiuProperties = qiNiuProperties;
        this.photoMapper = photoMapper;
    }

    @Override
    public String getQiNiuUpToken() {
        return QiNiuUtil.getUpToken(qiNiuProperties);
    }


    @Override
    public void savePhoto(Photo photo) {
        try {
            photoMapper.save(photo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WeException(ResultEnum.DB_UPDATE_ERROR);
        }
    }

    @Override
    public void savePhoto(String authorization, InputStream inputStream) throws Exception {
        HashMap<String, String> result = new HashMap<>(1);
        byte[] bodyByte = InputStreamUtil.inputStreamToByte(inputStream);
        // 1. 验证是否为七牛的回调;
        if (QiNiuUtil.isValidCallback(qiNiuProperties, authorization, bodyByte)) {
            // 2. 数据流转换成Object;
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            QiNiuPutRet qiNiuPutRet = gson.fromJson(new String(bodyByte), QiNiuPutRet.class);

            // 3. 将数据保存到数据库
            Photo photo = new Photo();
            photo.setUserId(qiNiuPutRet.getUserId());
            photo.setAlbumId(qiNiuPutRet.getAlbumId());
            photo.setName(qiNiuPutRet.getKey());
            photo.setPath(qiNiuPutRet.getKey());
            photo.setUrl(qiNiuProperties.getBaseUrl() + qiNiuPutRet.getKey());
            photo.setSize(qiNiuPutRet.getFsize());
            photo.setHeight(qiNiuPutRet.getHeight());
            photo.setWidth(qiNiuPutRet.getWidth());
            photo.setMimeType(qiNiuPutRet.getMimeType());
            photo.setEtag(qiNiuPutRet.getHash());
            photo.setLastModifiedDate(qiNiuPutRet.getLastModifiedDate());
            photoMapper.save(photo);
        } else {
            log.error("验证上传照片回调失败");
            throw new WeException(PARAM_ERROR.getCode(), "此请求不是七牛发起的");
        }
    }

    @Override
    public List<PhotosVo> getPhoto(Integer albumId) {
        List<Photo> photoList = photoMapper.selectPhotoByAlbumId(albumId);
        List<PhotosVo> photosVos = new ArrayList<>();
        for (Photo photo : photoList) {
            photo.setThumbnailUrl(QiNiuUtil.getDownloadUrl(qiNiuProperties, photo.getUrl() + "-thumbnail"));
            photo.setUrl(QiNiuUtil.getDownloadUrl(qiNiuProperties, photo.getUrl()));
            String date = DateUtils.getDate(photo.getCreateTime());
            boolean hasFlag = false;
            for (PhotosVo photosVo : photosVos) {
                if (photosVo.getDate().equals(date)) {
                    photosVo.getPhotos().add(photo);
                    hasFlag = true;
                    break;
                }
            }
            if (!hasFlag) {
                PhotosVo photosVo = new PhotosVo();
                photosVo.setDate(date);
                List<Photo> photos = new ArrayList<>();
                photos.add(photo);
                photosVo.setPhotos(photos);
                photosVos.add(photosVo);
            }
        }
        return photosVos;
    }

    @Override
    public void deletePhoto(Integer id, String key) {
        photoMapper.deletePhotoById(id);
        try {
            QiNiuUtil.deleteFile(qiNiuProperties, key);
        } catch (QiniuException e) {
            e.printStackTrace();
            if (e.response.statusCode != QiNiuCodeEnum.RESOURCES_NOT_EXIST.getCode()) {
                throw new WeException(ResultEnum.QI_NIU_DELETE_ERROR);
            }
        }
    }


}
